<template>
  <div class="video_box">
    <div class="liveinformation">
      <p><i class="el-icon-aim"></i> 当前观看人数：45人</p>
      <p><i class="el-icon-s-custom"></i> 当前关注人数：18人</p>
      <p><i class="el-icon-thumb"></i> 当前点赞人数：128人</p>
      <p><i class="el-icon-s-goods"></i> 当前下单人数：15人</p>
    </div>
    <div class="home">
      <div
        style="height: 100%; width: 100%; position: relative; margin: 0px auto"
      >
        <video
          id="videoCamera"
          :width="videoWidth"
          ref="video"
          :height="videoHeight"
          autoplay
        ></video>
        <canvas
          style="display: none"
          id="canvasCamera"
          :width="videoWidth"
          :height="videoHeight"
        ></canvas>
        <div v-if="imgSrc" class="img_bg_camera">
          <p>效果预览</p>
          <img :src="imgSrc" alt class="tx_img" />
        </div>

        <!-- 确保父元素是相对定位，弹幕容器是绝对定位 -->
        <v-barrage :arr="arr" :isPause="isPause" :percent="100"></v-barrage>
      </div>
      <div class="barrage-control">
        <div class="button">
          <input
            type="text"
            placeholder="回车发送"
            style="width: 30%; height: 40px; text-indent: 15px"
            v-model="sendContent"
            id="sendContent"
            @keyup.enter="sendBarrage"
          />
          <el-button
            type="success"
            id="sendBarrageBtn"
            style="margin-left: 25px"
            @click="sendBarrage"
            >发送</el-button
          >
          <select style="margin: 0px 12px; height: 40px" v-model="direction">
            <option value="default">默认</option>
            <option value="top">顶部</option>
          </select>
          <input type="checkbox" v-model="isJs" />
          <el-button @click="getCompetence()" type="danger"
            >打开摄像头</el-button
          >
          <el-button @click="stopNavigator()" type="danger" plain
            >强制关闭</el-button
          >
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import video from "../../assets/logo.png";
import video1 from "../../assets/logo.png";
import VBarrage from "@/components/VBarrage/index.vue";
// import {closLlive} from '../api/index'
export default {
  components: {
    VBarrage,
  },
  data() {
    return {
      video: video,
      video1: video1,
      arr: [],
      isPause: false,
      sendContent: null,
      isJs: false,
      direction: "default",
      videoWidth: 1500,
      videoHeight: 800,
      imgSrc: "",
      thisCancas: null,
      thisContext: null,
      thisVideo: null,
      openVideo: false,
    };
  },
  mounted() {
    this.initTestData();
    this.getCompetence(); //进入页面就调用摄像头
  },
  methods: {
    // 初始化模拟弹幕数据
    initTestData() {
      let arr = [
        "我的天呐！平凡之路的原唱都没法听了！",
        "从明天起，做一个勤奋的人",
        "最喜欢这个版本，中间穿插的哼唱， 还有最后的那句...谢谢你们...",
        " 最后我想送她一句话： 时间无言 如此这般 就一瞬间 后会无期！！",
        "一起嗨！！！",
      ];
      for (let i = 0; i < 6; i++) {
        for (let index = 0; index < 1000; index++) {
          if (index % 2 == 0) {
            this.arr.push({
              direction: "right",
              content: arr[parseInt(Math.random() * arr.length)],
            });
          } else {
            this.arr.push({
              direction: "default",
              content: arr[parseInt(Math.random() * arr.length)],
            });
          }
        }
      }
    },
    sendBarrage() {
      if (
        this.arr.length > 1 &&
        this.sendContent != "" &&
        this.sendContent != null
      ) {
        this.arr.unshift({
          content: this.sendContent,
          direction: this.direction,
          isSelf: true,
          style: {
            color: "red",
            fontSize: "25px",
          },
          isJs: this.isJs,
        });
      } else {
        this.arr.push({
          content: this.sendContent,
          direction: this.direction,
          isSelf: true,
          style: {
            color: "red",
          },
          isJs: this.isJs,
        });
      }
      this.sendContent = null;
    },
    // 调用权限（打开摄像头功能）
    getCompetence() {
      var _this = this;
      _this.thisCancas = document.getElementById("canvasCamera");
      _this.thisContext = this.thisCancas.getContext("2d");
      _this.thisVideo = document.getElementById("videoCamera");
      _this.thisVideo.style.display = "block";
      // 获取媒体属性，旧版本浏览器可能不支持mediaDevices，我们首先设置一个空对象
      if (navigator.mediaDevices === undefined) {
        navigator.mediaDevices = {};
      }
      // 一些浏览器实现了部分mediaDevices，我们不能只分配一个对象
      // 使用getUserMedia，因为它会覆盖现有的属性。
      // 这里，如果缺少getUserMedia属性，就添加它。
      if (navigator.mediaDevices.getUserMedia === undefined) {
        navigator.mediaDevices.getUserMedia = function (constraints) {
          // 首先获取现存的getUserMedia(如果存在)
          var getUserMedia =
            navigator.webkitGetUserMedia ||
            navigator.mozGetUserMedia ||
            navigator.getUserMedia;
          // 有些浏览器不支持，会返回错误信息
          // 保持接口一致
          if (!getUserMedia) {
            //不存在则报错
            return Promise.reject(
              new Error("getUserMedia is not implemented in this browser")
            );
          }
          // 否则，使用Promise将调用包装到旧的navigator.getUserMedia
          return new Promise(function (resolve, reject) {
            getUserMedia.call(navigator, constraints, resolve, reject);
          });
        };
      }
      var constraints = {
        audio: false,
        video: {
          width: this.videoWidth,
          height: this.videoHeight,
          transform: "scaleX(-1)",
        },
      };
      navigator.mediaDevices
        .getUserMedia(constraints)
        .then(function (stream) {
          // 旧的浏览器可能没有srcObject
          if ("srcObject" in _this.thisVideo) {
            _this.thisVideo.srcObject = stream;
          } else {
            // 避免在新的浏览器中使用它，因为它正在被弃用。
            _this.thisVideo.src = window.URL.createObjectURL(stream);
          }
          _this.thisVideo.onloadedmetadata = function (e) {
            _this.thisVideo.play();
          };
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 关闭摄像头
    stopNavigator() {
      this.thisVideo.srcObject.getTracks()[0].stop();
      this.$router.go(-1);
      //   closLlive().then(res=>{

      //   })
    },
    // base64转文件，此处没用到
    dataURLtoFile(dataurl, filename) {
      var arr = dataurl.split(",");
      var mime = arr[0].match(/:(.*?);/)[1];
      var bstr = atob(arr[1]);
      var n = bstr.length;
      var u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], filename, { type: mime });
    },
  },
};
</script>
x 
<style lang="scss" scoped>
.video_box {
  width: 100%;
  height: 100%;
  text-align: center;
  background: black;
  display: flex;
  .liveinformation {
    width: 15%;
    margin-top: 60px;
    p {
      padding: 20px;
      color: blue;
    }
  }
  video {
    width: 100%;
    height: 70%;
    text-align: center;
    position: relative;
    top: 0;
    left: 0;
  }
  .home {
    width: 70%;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }
}
.barrage-control {
  text-align: center;
  margin: 10px 0px;
}
.button {
  width: 100%;
  display: flex;
  align-items: center;
}
</style>